package com.itdr.protal.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itdr.common.Const;
import com.itdr.common.ServerResponse;
import com.itdr.pojo.*;
import com.itdr.pojo.vo.OrderItemVO;
import com.itdr.pojo.vo.OrderVO;
import com.itdr.pojo.vo.ShippingVO;
import com.itdr.protal.mapper.*;
import com.itdr.protal.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itdr.utils.VOUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author AirZhang
 * @since 2020-10-20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    OrderMapper orderMapper;
    @Resource
    CartMapper cartMapper;
    @Resource
    ProductMapper productMapper;
    @Resource
    OrderItemMapper orderItemMapper;
    @Resource
    ShippingMapper shippingMapper;

//    生成订单号
    private Long getOrderId() {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();
        return id;
    }
//    生成订单详情
    private OrderItem getOrderItem(Integer uid, Long orderId, Cart cart, Product product) {
        OrderItem orderItem = new OrderItem();
        orderItem.setUserId(uid);
        orderItem.setOrderNo(orderId);
        orderItem.setProductId(cart.getProductId());
        orderItem.setProductName(product.getName());
        orderItem.setProductImage(product.getMainImage());
        orderItem.setCurrentUnitPrice(product.getPrice());
        orderItem.setQuantity(cart.getQuantity());
        BigDecimal mul = NumberUtil.mul(product.getPrice(), cart.getQuantity());
        orderItem.setTotalPrice(mul);
        orderItem.setCreateTime(new Date());
        orderItem.setUpdateTime(new Date());
        return orderItem;
    }
//    生成订单
    private Order getOrder(Integer uid, Long orderId, Integer shippingId, BigDecimal payment) {
        Order o = new Order();
        o.setUserId(uid);
        o.setOrderNo(orderId);
        o.setShippingId(shippingId);
        o.setPayment(payment);
        o.setPaymentType(1);
        o.setPostage(0);
        o.setStatus(10);
        o.setCreateTime(new Date());
        o.setUpdateTime(new Date());
        return o;
    }



    @Override
    public ServerResponse listAll(Integer uid, Integer pageNum, Integer pageSize,Integer status) {
        // 创建一个空容器，用来存储最终返回的数据
        List voList = new ArrayList<>();

        // 查询当前用户所有订单数据，并且分页
        Map m = new HashMap();
        m.put("user_id",uid);
        m.put("status",status);
        Page<Order> orderPage = orderMapper.selectPage(new Page<Order>(pageNum,pageSize), new QueryWrapper<Order>().allEq(m));
        // 从上面的分页对象中，取出订单集合
        List<Order> records = orderPage.getRecords();
        // 遍历订单集合
        for (Order or : records) {
            // 创建一个空容器，用来存储订单详情VO类数据
            List<OrderItemVO> itemVOList = new ArrayList<>();
            // 根据收货地址ID获取收货地址信息
            Shipping shipping = shippingMapper.selectById(or.getShippingId());
            // 处理原始的收货地址信息，封装成VO类
            ShippingVO shippingVO = VOUtil.getShippingVO(shipping);
            // 查询这次遍历的订单，所对应的订单详情数据
            List<OrderItem> itemList = orderItemMapper.selectList(new QueryWrapper<OrderItem>().eq("order_no", or.getOrderNo()));
            // 遍历订单详情集合，处理成对应的VO类
            for (OrderItem orderItem : itemList) {
                // 使用工具类进行VO类封装
                OrderItemVO orderItemVO = VOUtil.getOrderItemVO(orderItem);
                // 每处理好一个，就放到一开始创建好的空容器中
                itemVOList.add(orderItemVO);
            }
            // 使用工具类，封装订单VO类对象
            OrderVO orderVO = VOUtil.getOrderVO(or.getOrderNo(), or.getPayment(), shippingVO, or.getStatus(), itemVOList);
            // 每处理好一个，就放到一个开始创建好的空容器中
            voList.add(orderVO);
        }
        // 将存放好数据的voList容器，重新赋值给分页对象，替换掉原始的分页数据
        orderPage.setRecords(voList);
        // 返回成功数据
        return ServerResponse.toSuccess(orderPage);
    }

    @Override
    public ServerResponse insertOne(Integer uid, Integer shippingId, BigDecimal payment,Integer pageNum,Integer pageSize) {
        // 1.点击结算，查询当前用户购物车中选中商品
        Map m = new HashMap();
        m.put("user_id", uid);
        m.put("checked", 1);
        List<Cart> cartList = cartMapper.selectList(new QueryWrapper<Cart>().allEq(m));
        if(cartList.size() == 0){
            return ServerResponse.toFail(Const.OrderEnum.NO_ANY_PRODUCT.getCode(),Const.OrderEnum.NO_ANY_PRODUCT.getDesc());
        }
        // 2.生成订单号，雪花算法
        Long orderId = getOrderId();
        // 3.插入订单数据
        Order o = getOrder(uid, orderId, shippingId, payment);
        int insert = orderMapper.insert(o);
        if (insert <= 0) {
            return ServerResponse.toFail(Const.OrderEnum.FAIL_ADD_ORDER.getCode(), Const.OrderEnum.FAIL_ADD_ORDER.getDesc());
        }
        // 4.当订单插入成功的情况下
        for (Cart cart : cartList) {
            // 1.创建订单详情
            Product product = productMapper.selectById(cart.getProductId());
            OrderItem orderItem = getOrderItem(uid, orderId, cart, product);
            int oit = orderItemMapper.insert(orderItem);
            if (oit <= 0) {
                return ServerResponse.toFail(Const.OrderEnum.FAIL_ADD_ORDERITEM.getCode(), Const.OrderEnum.FAIL_ADD_ORDERITEM.getDesc());
            }
            // 2.清空购物车中对应的数据
            int pi = cartMapper.deleteById(cart.getId());
            if (pi <= 0) {
                return ServerResponse.toFail(Const.CartEnum.DELETE_CART.getCode(), Const.CartEnum.DELETE_CART.getDesc());
            }
            // 3.锁定商品库存
            Integer num = product.getStock() - cart.getQuantity();
            if (num < 0) {
                num = product.getStock();
            }
            int update = productMapper.update(null, new UpdateWrapper<Product>().set("stock", num).eq("id", product.getId()));
            if (update <= 0) {
                return ServerResponse.toFail(Const.ProductEnum.FAIL_UPDATE.getCode(), Const.ProductEnum.FAIL_UPDATE.getDesc());
            }
        }

        // 创建一个空容器，用来存储订单详情VO类数据
        List<OrderItemVO> itemVOList = new ArrayList<>();
        // 根据收货地址ID获取收货地址信息
        Shipping shipping = shippingMapper.selectById(o.getShippingId());
        // 处理原始的收货地址信息，封装成VO类
        ShippingVO shippingVO = VOUtil.getShippingVO(shipping);
        // 查询这次遍历的订单，所对应的订单详情数据
        List<OrderItem> itemList = orderItemMapper.selectList(new QueryWrapper<OrderItem>().eq("order_no", o.getOrderNo()));
        // 遍历订单详情集合，处理成对应的VO类
        for (OrderItem orderItem : itemList) {
            // 使用工具类进行VO类封装
            OrderItemVO orderItemVO = VOUtil.getOrderItemVO(orderItem);
            // 每处理好一个，就放到一开始创建好的空容器中
            itemVOList.add(orderItemVO);
        }
        // 使用工具类，封装订单VO类对象
        OrderVO orderVO = VOUtil.getOrderVO(o.getOrderNo(), o.getPayment(), shippingVO, o.getStatus(), itemVOList);
        return ServerResponse.toSuccess(orderVO);
    }


}
